

//
//  Home.swift
//  myweibo
//
//  Created by myd on 15/12/15.
//  Copyright © 2015年 myd1. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


enum statuscellre : String{
    case homecellorg = "homecellorg"
    case homeccell = "homeccell"
}


class Home: besiTableViewController {
    lazy var arr : NSMutableArray = {
   let  ar = NSMutableArray()
        return ar
    }()
       let con = myrefresh()

    
    override func viewDidLoad() {
        super.viewDidLoad()
   
        if !user1.loadboo()
        {
       return
        }
        setrow()
        self.tableView.tableFooterView = homefootview()
        self.tableView.tableFooterView?.hidden = true
//        loaddata()
        setnav()
        refreshControl = con
        con.beginRefreshing()
        setloaddata()
        con.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    
   
    
  private func setnav()
   {
//    let users = user1.loadtoken()
//    navigationItem.title = users?.screen_name
    tableView.registerClass(homecellorg.self, forCellReuseIdentifier: statuscellre.homecellorg.rawValue)
     tableView.registerClass(homeccell.self, forCellReuseIdentifier: statuscellre.homeccell.rawValue)
    
    let left = UIBarButtonItem.setna("navigationbar_friendsearch")
    left.addTarget(self, action: "friend", forControlEvents: UIControlEvents.TouchUpInside)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: left)
    
    let right = UIBarButtonItem.setna("navigationbar_pop")
    right.addTarget(self, action: "twodimensionalcode", forControlEvents: UIControlEvents.TouchUpInside)
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: right)
    let title = hometitlebutton(image: "navigationbar_arrow_up", and: "navigationbar_arrow_dowm", title:user1.loadtoken()?.screen_name ?? "没有加载到用户名")
    title.addTarget(self, action: "chilktitleview:", forControlEvents: UIControlEvents.TouchUpInside)
    navigationItem.titleView = title
    }
    func chilktitleview(btn : UIButton)
    {
       

       UIView.animateWithDuration(0.25, animations: { () -> Void in
        btn.imageView!.transform = CGAffineTransformRotate(btn.imageView!.transform,btn.selected ? CGFloat(-M_PI+0.001) : CGFloat(+M_PI-0.001))
       })
             btn.selected = !btn.selected
            return
    }
    
    
    func friend()
    {
   
    }
    func twodimensionalcode()
    {
   
    }

    
  func setrow()
  {
           tableView.estimatedRowHeight=200
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//          tableView.rowHeight=150
    }
//func loaddata()
//{
//    
//    
//    OauthNetwork.sharedinstance.loadweibomessage { (resuit, Error) -> () in
//        if resuit == nil || Error != nil
//        {
//        
//            SVProgressHUD.showErrorWithStatus("微博数据读取错误")
//            return
//        }
//        else
//        {
//            self.arr =  homeweimessage.homeweimessage1(resuit!)!
//            self.tableView.reloadData()
//        }
//    }
//    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return arr.count
    }
    
    
  func setloaddata()
  {

    con.addTarget(self, action: "loadup:", forControlEvents: UIControlEvents.ValueChanged)
    }
    func loadup(con : myrefresh)
    {
        con.re.view.hidden = true
        var since_id : Int = 0
        if self.arr.count != 0 {
        let ms = self.arr.firstObject as! homeweimessage
           since_id = ms.id ?? 0}
        homeweimessage.loaddate(since_id , max_id:  0){ (resuit, Error) -> () in
                   con.endRefreshing()
            if resuit==nil || Error != nil
            {
         
               SVProgressHUD.showErrorWithStatus("网络不行啊")
           return
            }
            let count = resuit?.count ?? 0
            if since_id > 0
            {
           self.showcon(count)
            }
            if count == 0
            {
           return
            }
            if since_id>0
            {
           self.arr.insertObject(resuit!, atIndex: 0)
            }else
            {
           self.arr = resuit!
                self.showcon(resuit!.count)
                self.tableView.reloadData()
            }
//            con.re.view.hidden = false
        }
    }
    func showcon(con : Int)
    {
   let lab = UILabel()
        lab.textAlignment = NSTextAlignment.Center
        self.navigationController!.view.insertSubview(lab, belowSubview: (self.navigationController?.navigationBar)!)
        lab.frame = CGRectMake(0,0,UIScreen.mainScreen().bounds.width, 35)
        lab.backgroundColor = UIColor.orangeColor()
        lab.text = con == 0 ? "已经是最新的微博了" : "更新了\(con)条微博"
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            lab.frame = CGRectMake(0, 64, lab.bounds.size.width, lab.bounds.size.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, delay: 1, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
                       lab.frame = CGRectMake(0, 0, lab.bounds.size.width, lab.bounds.size.height)
                    }, completion: { (_) -> Void in
                        lab.removeFromSuperview()
                })
        }
        
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
              let model = arr[indexPath.row] as! homeweimessage
        let isid = model.isor()
        let cell = tableView.dequeueReusableCellWithIdentifier(isid, forIndexPath: indexPath) as! hometitlecell
        cell.weibodata = model
        return cell
    }
 

    
    override func scrollViewDidScroll(scrollView: UIScrollView) {
     
        if arr.count == 0
        {
       return
        }
     let of = scrollView.contentOffset.y
    let conoff = scrollView.contentSize.height + scrollView.contentInset.bottom - (self.tableView.tableFooterView?.bounds.height)! - scrollView.frame.height
        
        if of <= conoff+35
        {return}
       
        
  loaddatabefor()
    }
    
    func loaddatabefor()
    {
        if self.tableView.tableFooterView?.hidden == false
        {
        return
        }
        self.tableView.tableFooterView?.hidden = false
        let max = self.arr.lastObject as? homeweimessage
        if self.con.refreshing{
            return
        }
        homeweimessage.loaddate(0 , max_id:max!.id){ (resuit, Error) -> () in
        if resuit == nil || Error != nil
        {
           SVProgressHUD.showErrorWithStatus("加载数据出错了")
            return
            }
        self.arr.addObjectsFromArray(resuit! as NSArray as [AnyObject] )
            self.tableView.reloadData()
            self.showcon(resuit!.count)
        self.tableView.tableFooterView?.hidden = true
        }
    }
    
//    func loaddatabefor()
//    {
//        let urlstring = "https://api.weibo.com/2/statuses/friends_timeline.json"
//        let tok = user1.loadtoken()?.access_token!
//        var dic = ["access_token" : tok!]
//        if self.arr.count != 0 {
//            let web = self.arr.lastObject as! homeweimessage
//            dic ["max_id"] = web.id as? String
//        }
//        
//        let manager = AFHTTPSessionManager()
//        manager.GET(urlstring, parameters: dic, success: { (_, result) -> Void in
//            let ar = homeweimessage.homeweimessage1(result as! [String : AnyObject]) as NSArray
//            self.arr.addObjectsFromArray(ar as [AnyObject])
//           self.tableView.reloadData()
//            self.showcon(ar.count)
//               self.tableView.tableFooterView?.hidden = true
//            self.tableView.reloadData()
//            }) { (_, error : NSError) -> Void in
//      
//                print("加载错误")
//        }
//    }

}
